import { SceneType } from "../../../../../../Core/Module/Entity/SceneType";
import { Log } from "../../../../../../Core/Module/Log/Log";
import { SerializeHelper } from "../../../../../../Core/Serialize/SerializeHelper";
import { MessageHandlerAttribute } from "../../../../../../Decorator/Decorator";
import { G2R_GetLoginKey, R2G_GetLoginKey } from "../../../../../Model/Generate/Share/Message/InnerMessage_S_20001";
import { C2R_Login, R2C_Login } from "../../../../../Model/Generate/Share/Message/OuterMessage_C_10001";
import { ActorMessageSenderComponent } from "../../../../../Model/Server/Module/Actor/ActorMessageSenderComponent";
import { AMRpcHandler } from "../../../../../Model/Server/Module/Message/AMRpcHandler";
import { ErrorCode } from "../../../../../Model/Share/Module/Message/ErrorCode";
import { Session } from "../../../../../Model/Share/Module/Message/Session";
import { RealmGateAddressHelper } from "./RealmGateAddressHelper";

@MessageHandlerAttribute(SceneType.Realm, C2R_Login, R2C_Login)
export class C2R_LoginHandler extends AMRpcHandler<C2R_Login, R2C_Login> {

    protected async Run(session: Session, request: C2R_Login, response: R2C_Login) {
        response = SerializeHelper.PackMessage(R2C_Login, response);
        response.Error = ErrorCode.ERR_Success;

        // 随机分配一个Gate
        const config = RealmGateAddressHelper.GetGate(session.DomainZone(), 1);
        Log.Debug(`gate address: ${JSON.stringify(config)}`);

        // 向gate请求一个key,客户端可以拿着这个key连接gate
        const r2gLoginKey = new R2G_GetLoginKey();
        r2gLoginKey.Account = request.Account;
        const g2RGetLoginKey = <G2R_GetLoginKey>await ActorMessageSenderComponent.Instance.Call(config.InstanceId, r2gLoginKey);

        // console.log(`ActorMessageSenderComponent.R2G_GetLoginKey`);
        // console.log(g2RGetLoginKey);

        response.Address = config.InnerIPOutPort;
        response.Key = g2RGetLoginKey.Key;
        response.GateId = g2RGetLoginKey.GateId;

        // console.log(`C2R_LoginHandler`);
        // console.log(request);
        // console.log(response);
    }

}